<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>应用上下文Context | East'blog</title><meta name="author" content="侯玉东"><meta name="copyright" content="侯玉东"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="应用上下文">
<meta property="og:type" content="article">
<meta property="og:title" content="应用上下文Context">
<meta property="og:url" content="https://houyudong1989.gitee.io/blog/2023/11/01/harmonyOS/context/index.html">
<meta property="og:site_name" content="East&#39;blog">
<meta property="og:description" content="应用上下文">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://houyudong1989.gitee.io/blog/img/library1.jpeg">
<meta property="article:published_time" content="2023-10-31T16:00:00.000Z">
<meta property="article:modified_time" content="2023-11-28T09:38:19.138Z">
<meta property="article:author" content="侯玉东">
<meta property="article:tag" content="harmonyOS context">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://houyudong1989.gitee.io/blog/img/library1.jpeg"><link rel="shortcut icon" href="/blog/img/head.jpg"><link rel="canonical" href="https://houyudong1989.gitee.io/blog/2023/11/01/harmonyOS/context/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/blog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '应用上下文Context',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-11-28 17:38:19'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (true) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/img/head.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">70</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">18</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友联</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('/blog/img/library2.jpeg')"><nav id="nav"><span id="blog-info"><a href="/blog/" title="East'blog"><img class="site-icon" src="/blog/img/head.jpg"/><span class="site-name">East'blog</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友联</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">应用上下文Context</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-10-31T16:00:00.000Z" title="发表于 2023-11-01 00:00:00">2023-11-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-11-28T09:38:19.138Z" title="更新于 2023-11-28 17:38:19">2023-11-28</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/harmonyOS/">harmonyOS</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="应用上下文Context"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h1><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">* Context是应用中对象的上下文，提供了应用的一些基础信息，如resourceManager（资源管理）、applicationInfo（当前应用信息）、dir（应用开发路径）、area（文件分区）等，以及应用的一些基本方法，如createBundleContext()、getApplicationContext()等。</span><br><span class="line">* UIAbility组件和各种ExtensionAbility派生类组件都有各自不同的Context类。</span><br></pre></td></tr></table></figure>

<blockquote>
<p>context 继承关系</p>
</blockquote>
<p><img src="1700486429377.png" alt="1700486429377"></p>
<blockquote>
<p>context 持有关系</p>
</blockquote>
<p><img src="1700486659507.png" alt="1700486659507"></p>
<h1 id="context-使用方式"><a href="#context-使用方式" class="headerlink" title="context 使用方式"></a>context 使用方式</h1><h2 id="ApplicationContext"><a href="#ApplicationContext" class="headerlink" title="ApplicationContext"></a>ApplicationContext</h2><blockquote>
<p>应用级别的Context。ApplicationContext在基类Context的基础上提供了订阅应用内Ability的生命周期的变化、订阅系统内存变化和订阅应用内系统环境的变化的能力，在UIAbility、ExtensionAbility、AbilityStage中均可以获取。</p>
</blockquote>
<blockquote>
<p>示例</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//其中，this.context代表在UIAbility、ExtensionAbility、AbilityStage中获取的UIAbilityContext、ExtensionAbilityContext、AbilityStageContext</span><br><span class="line">let applicationContext = this.context.getApplicationContext();</span><br></pre></td></tr></table></figure>

<blockquote>
<p>注册监听应用内生命周期 示例</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">import UIAbility from &#x27;@ohos.app.ability.UIAbility&#x27;;</span><br><span class="line"></span><br><span class="line">let lifecycleId;</span><br><span class="line"></span><br><span class="line">export default class EntryAbility extends UIAbility &#123;</span><br><span class="line">    onCreate() &#123;</span><br><span class="line">        console.log(&#x27;MyAbility onCreate&#x27;);</span><br><span class="line">        let AbilityLifecycleCallback = &#123;</span><br><span class="line">            onAbilityCreate(ability) &#123;</span><br><span class="line">   </span><br><span class="line">            &#125;,</span><br><span class="line">            onWindowStageCreate(ability, windowStage) &#123;</span><br><span class="line">   </span><br><span class="line">            &#125;,</span><br><span class="line">            onWindowStageActive(ability, windowStage) &#123;</span><br><span class="line">   </span><br><span class="line">            &#125;,</span><br><span class="line">            onWindowStageInactive(ability, windowStage) &#123;</span><br><span class="line">  </span><br><span class="line">            &#125;,</span><br><span class="line">            onWindowStageDestroy(ability, windowStage) &#123;</span><br><span class="line">  </span><br><span class="line">            &#125;,</span><br><span class="line">            onAbilityDestroy(ability) &#123;</span><br><span class="line">  </span><br><span class="line">            &#125;,</span><br><span class="line">            onAbilityForeground(ability) &#123;</span><br><span class="line">   </span><br><span class="line">            &#125;,</span><br><span class="line">            onAbilityBackground(ability) &#123;</span><br><span class="line">   </span><br><span class="line">            &#125;,</span><br><span class="line">            onAbilityContinue(ability) &#123;</span><br><span class="line">   </span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        // 1.通过context属性获取applicationContext</span><br><span class="line">        let applicationContext = this.context.getApplicationContext();</span><br><span class="line">        // 2.通过applicationContext注册监听应用内生命周期</span><br><span class="line">        lifecycleId = applicationContext.on(&#x27;abilityLifecycle&#x27;, AbilityLifecycleCallback);</span><br><span class="line">        console.log(&#x27;registerAbilityLifecycleCallback number: &#x27; + JSON.stringify(lifecycleId));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>取消监听应用内声明周期 示例</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">import Ability from &#x27;@ohos.app.ability.UIAbility&#x27;;</span><br><span class="line"></span><br><span class="line">let lifecycleId;</span><br><span class="line"></span><br><span class="line">export default class MyAbility extends Ability &#123;</span><br><span class="line">    onDestroy() &#123;</span><br><span class="line">        let applicationContext = this.context.getApplicationContext();</span><br><span class="line">        applicationContext.off(&#x27;abilityLifecycle&#x27;, lifecycleId);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>注册对系统环境变化的监听 示例</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">import UIAbility from &#x27;@ohos.app.ability.UIAbility&#x27;;</span><br><span class="line"></span><br><span class="line">let callbackId;</span><br><span class="line">export default class EntryAbility extends UIAbility &#123;</span><br><span class="line">    onCreate() &#123; </span><br><span class="line">        globalThis.applicationContext = this.context.getApplicationContext();</span><br><span class="line">        let environmentCallback = &#123;</span><br><span class="line">            onConfigurationUpdated(config)&#123;</span><br><span class="line">     </span><br><span class="line">            &#125;,</span><br><span class="line">            onMemoryLevel(level)&#123;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        // 1.获取applicationContext</span><br><span class="line">        let applicationContext = globalThis.applicationContext;</span><br><span class="line">        // 2.通过applicationContext注册监听应用内生命周期</span><br><span class="line">        callbackId = applicationContext.on(&#x27;environment&#x27;, environmentCallback);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>注册对系统环境变化的监听 示例</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">import Ability from &#x27;@ohos.app.ability.UIAbility&#x27;;</span><br><span class="line"></span><br><span class="line">let callbackId;</span><br><span class="line">export default class MyAbility extends Ability &#123;</span><br><span class="line">    onDestroy() &#123;</span><br><span class="line">        let applicationContext = this.context.getApplicationContext();</span><br><span class="line">        applicationContext.off(&#x27;environment&#x27;, callbackId);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>杀死应用所在的进程 示例</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">let applicationContext = this.context.getApplicationContext();</span><br><span class="line">applicationContext.killProcessesBySelf().then((data) =&gt; &#123; </span><br><span class="line">&#125;).catch((error) =&gt; &#123; </span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>思考？？</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">在具体业务过程中，很多地方都可能会需要用到页面的声明周期，比如在页面加载的时候请求网络，页面消失的时候取消加载，这时候我们就可以通过该方法来进行监听页面的生命周期</span><br></pre></td></tr></table></figure>

<h2 id="UIAbilityContext"><a href="#UIAbilityContext" class="headerlink" title="UIAbilityContext"></a>UIAbilityContext</h2><blockquote>
<p>每个UIAbility中都包含了一个UIAbilityContext属性，UIAbilityContext模块提供允许访问该UIAbility的资源的能力，提供获取Ability的配置信息、操作Ability启动、停止、获取caller通信接口、应用向用户申请授权等能力等。</p>
</blockquote>
<h3 id="获取-UIAbilityContext"><a href="#获取-UIAbilityContext" class="headerlink" title="获取 UIAbilityContext"></a>获取 UIAbilityContext</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">// UIAbility自身包含了UIAbilityContext，通过this.context即可获得。</span><br><span class="line">import UIAbility from &#x27;@ohos.app.ability.UIAbility&#x27;;</span><br><span class="line">export default class EntryAbility extends UIAbility &#123;</span><br><span class="line">    onCreate(want, launchParam) &#123;</span><br><span class="line">        let uiAbilityContext = this.context;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<blockquote>
<p>源码中定义了UIAbilityContext</p>
</blockquote>
<p><img src="1700528500936.png" alt="1700528500936"></p>
<h3 id="启动一个新的-UIAbility"><a href="#启动一个新的-UIAbility" class="headerlink" title="启动一个新的 UIAbility"></a>启动一个新的 UIAbility</h3><blockquote>
<p>通过调用UIAbilityContext.startAbility方法，可以启动一个新的UIAbility实例。</p>
</blockquote>
<blockquote>
<p>使用规则：</p>
</blockquote>
<ul>
<li>调用方应用位于后台时，使用该接口启动Ability需申请ohos.permission.START_ABILITIES_FROM_BACKGROUND权限</li>
<li>目标Ability的visible属性若配置为false，调用方应用需申请ohos.permission.START_INVISIBLE_ABILITY权限</li>
<li>组件启动规则详见：组件启动规则（Stage模型）</li>
</ul>
<blockquote>
<p>示例</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line">// 启动ability，在某个点击事件中调用</span><br><span class="line"> let want = &#123;</span><br><span class="line">      deviceId: &#x27;&#x27;, // deviceId为空表示本设备</span><br><span class="line">      bundleName: &#x27;com.extreme.test&#x27;,//应用包名</span><br><span class="line">      abilityName: &#x27;MainAbility&#x27;,//要打开的ability页面名称</span><br><span class="line">      moduleName: &#x27;entry&#x27;, // 模块名称，moduleName非必选</span><br><span class="line">      parameters: &#123;</span><br><span class="line">        keyForString: &#x27;str&#x27;,</span><br><span class="line">        keyForInt: 100,</span><br><span class="line">        keyForDouble: 99.99,</span><br><span class="line">        keyForBool: true,</span><br><span class="line">        keyForObject: &#123;</span><br><span class="line">          keyForObjectString: &#x27;str&#x27;,</span><br><span class="line">          keyForObjectInt: -200,</span><br><span class="line">          keyForObjectDouble: 35.5,</span><br><span class="line">          keyForObjectBool: false,</span><br><span class="line">        &#125;,</span><br><span class="line">        keyForArrayString: [&#x27;str1&#x27;, &#x27;str2&#x27;, &#x27;str3&#x27;],</span><br><span class="line">        keyForArrayInt: [100, 200, 300, 400],</span><br><span class="line">      &#125;,</span><br><span class="line">    &#125;;</span><br><span class="line">    let options = &#123;</span><br><span class="line">      displayId: 0,//屏幕编号，意思是在指定屏幕进行打开，如果手机有多个屏幕，可以指定在主屏或是副屏进行打开</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    try &#123;</span><br><span class="line">      this.context.startAbility(want, options)</span><br><span class="line">        .then((data) =&gt; &#123;</span><br><span class="line">          // 执行正常业务,通常data为undefined，在这里处理一些收尾工作，也可以不要</span><br><span class="line">          console.log(&#x27;startAbility succeed&#x27;);</span><br><span class="line">        &#125;)</span><br><span class="line">        .catch((error) =&gt; &#123;</span><br><span class="line">          // 处理业务逻辑错误</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125; catch (paramError) &#123;</span><br><span class="line">      // 处理入参错误异常</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">// 在启动的页面中获取传递的参数</span><br><span class="line">export default class SecondAbility extends UIAbility &#123;</span><br><span class="line">  onCreate(want, launchParam) &#123;</span><br><span class="line">    // hilog.info(0x0000, &#x27;testTag&#x27;, &#x27;%&#123;public&#125;s&#x27;, &#x27;Ability onCreate&#x27;);</span><br><span class="line">    if (typeof want !== &quot;undefined&quot;) &#123;</span><br><span class="line">      hilog.info(0x0000, &#x27;east&#x27;, &#x27;%&#123;public&#125;s&#x27;,want.parameters.keyForString);</span><br><span class="line">      hilog.info(0x0000, &#x27;east&#x27;, &#x27;%&#123;public&#125;d&#x27;,want.parameters.keyForInt);</span><br><span class="line">      hilog.info(0x0000, &#x27;east&#x27;, &#x27;%&#123;public&#125;d&#x27;,want.parameters.keyForDouble);</span><br><span class="line">      hilog.info(0x0000, &#x27;east&#x27;, &#x27;%&#123;public&#125;s&#x27;,want.parameters.keyForObject);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<blockquote>
<blockquote>
<p>疑问？</p>
<ul>
<li>通过ability启动另一个ability，在任务栈中会出现两个页面，如果我希望他们之间只有一个应该怎么办呢？</li>
<li>一个hap是否只允许有一个ability？<ul>
<li>默认只有一个，你可以通过手动的方式去添加，但是并不建议这样做，推荐使用一个ability获得最佳体验</li>
</ul>
</li>
</ul>
</blockquote>
</blockquote>
<h3 id="获取-UIAbility-返回结果"><a href="#获取-UIAbility-返回结果" class="headerlink" title="获取 UIAbility 返回结果"></a>获取 UIAbility 返回结果</h3><blockquote>
<p>AUIAbility通过startAbilityForResult开启一个新的BUIAbility时，当新的BUIAbility要结束工作时调用<a target="_blank" rel="noopener" href="https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-inner-application-uiabilitycontext-0000001478341321-V3#ZH-CN_TOPIC_0000001523648914__uiabilitycontextterminateselfwithresult">terminateSelfWithResult</a>可以终止BUIAbility并且返回结果给AUIAbility。</p>
</blockquote>
<blockquote>
<p>使用规则：</p>
</blockquote>
<ul>
<li>调用方应用位于后台时，使用该接口启动Ability需申请ohos.permission.START_ABILITIES_FROM_BACKGROUND权限</li>
<li>目标Ability的visible属性若配置为false，调用方应用需申请ohos.permission.START_INVISIBLE_ABILITY权限</li>
<li>组件启动规则详见：组件启动规则（Stage模型）</li>
</ul>
<blockquote>
<p>示例</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">// AUIAbility 页面ets</span><br><span class="line">  let want = &#123;</span><br><span class="line">              deviceId: &#x27;&#x27;, // deviceId为空表示本设备</span><br><span class="line">              bundleName: &#x27;com.ciyun.myapplication&#x27;,</span><br><span class="line">              abilityName: &#x27;SecondAbility&#x27;,</span><br><span class="line">              moduleName: &#x27;second&#x27;, // moduleName非必选</span><br><span class="line">              parameters: &#123;</span><br><span class="line">                keyForString: &#x27;str&#x27;,</span><br><span class="line">                keyForInt: 100,</span><br><span class="line">                keyForDouble: 99.99,</span><br><span class="line">                keyForBool: true,</span><br><span class="line">              &#125;,</span><br><span class="line">            &#125;;</span><br><span class="line">            let options = &#123;</span><br><span class="line">              displayId: 0,//屏幕编号，意思是在指定屏幕进行打开，如果手机有哥哥屏幕，可以指定在主屏或是副屏进行打开</span><br><span class="line">            &#125;;</span><br><span class="line">            try &#123;</span><br><span class="line">              let that =this</span><br><span class="line">              this.uicontext.startAbilityForResult(want, options)</span><br><span class="line">                .then((result) =&gt; &#123;</span><br><span class="line">                  // BUIAbility返回的数据在这里做处理</span><br><span class="line">                 if(result.resultCode == 100)&#123;</span><br><span class="line">                   that.message = result.want.parameters.resultdata</span><br><span class="line">                 &#125;</span><br><span class="line">                &#125;)</span><br><span class="line">                .catch((error) =&gt; &#123;</span><br><span class="line">                  // 处理业务逻辑错误</span><br><span class="line">                &#125;);</span><br><span class="line">            &#125; catch (paramError) &#123;</span><br><span class="line">              // 处理入参错误异常</span><br><span class="line">            &#125;</span><br><span class="line">// BUIAbility 页面ets</span><br><span class="line">  let want = &#123;</span><br><span class="line">              bundleName: &#x27;com.ciyun.myapplication&#x27;,</span><br><span class="line">              abilityName: &#x27;EntryAbility&#x27;,</span><br><span class="line">              moduleName: &#x27;entry&#x27;, // moduleName非必选</span><br><span class="line">              parameters: &#123;</span><br><span class="line">                resultdata: &#x27;这是我返回的数据&#x27;</span><br><span class="line">              &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            let resultCode = 100;</span><br><span class="line">            // 返回给接口调用方AbilityResult信息</span><br><span class="line">            let abilityResult = &#123;</span><br><span class="line">              want,</span><br><span class="line">              resultCode</span><br><span class="line">            &#125;</span><br><span class="line">            try &#123;</span><br><span class="line">              this.uicontext.terminateSelfWithResult(abilityResult)</span><br><span class="line">                .then((data) =&gt; &#123;</span><br><span class="line">                  // 执行正常业务，通常不用做什么，可以做ability销毁的一些工作</span><br><span class="line">                &#125;)</span><br><span class="line">                .catch((error) =&gt; &#123;</span><br><span class="line">                  // 处理业务逻辑错误 </span><br><span class="line">                &#125;);</span><br><span class="line">            &#125; catch (paramError) &#123;</span><br><span class="line">              // 处理入参错误异常 </span><br><span class="line">            &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="AbilityStageContext"><a href="#AbilityStageContext" class="headerlink" title="AbilityStageContext"></a>AbilityStageContext</h2><blockquote>
<p>AbilityStageContext是AbilityStage的上下文环境，继承自<a target="_blank" rel="noopener" href="https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-inner-application-context-0000001427744988-V3">Context</a>。</p>
<p>AbilityStageContext提供允许访问特定于abilityStage的资源的能力，包括获取AbilityStage对应的ModuleInfo对象、环境变化对象。</p>
</blockquote>
<h2 id="ServiceExtensionContext"><a href="#ServiceExtensionContext" class="headerlink" title="ServiceExtensionContext"></a>ServiceExtensionContext</h2><blockquote>
<p>仅对系统应用开放</p>
</blockquote>
<blockquote>
<p>官方文档</p>
</blockquote>
<p><a target="_blank" rel="noopener" href="https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/application-context-stage-0000001427744560-V3">应用上下文Context</a></p>
<p><a target="_blank" rel="noopener" href="https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-inner-application-applicationcontext-0000001477981357-V3">ApplicationContext</a></p>
<p><a target="_blank" rel="noopener" href="https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-inner-application-uiabilitycontext-0000001478341321-V3#ZH-CN_TOPIC_0000001523648914__uiabilitycontextstartability-1">UIAbilityContext</a></p>
<p><a target="_blank" rel="noopener" href="https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/js-apis-inner-application-abilitystagecontext-0000001478181577-V3">AbilityStageContext</a></p>
<p><a target="_blank" rel="noopener" href="https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/is-inner-application-accessibilityextensioncontext-0000001544584057-V3">AccessibilityExtensionContext (辅助功能扩展上下文)</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://houyudong1989.gitee.io/blog">侯玉东</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://houyudong1989.gitee.io/blog/2023/11/01/harmonyOS/context/">https://houyudong1989.gitee.io/blog/2023/11/01/harmonyOS/context/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://houyudong1989.gitee.io/blog" target="_blank">East'blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/harmonyOS-context/">harmonyOS context</a></div><div class="post_share"><div class="social-share" data-image="/blog/img/library1.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2023/11/05/harmonyOS/hdc/" title="hdc 使用帮助"><img class="cover" src="/blog/img/library1.jpeg" onerror="onerror=null;src='/blog/img/friend_404.gif'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">hdc 使用帮助</div></div></a></div><div class="next-post pull-right"><a href="/blog/2023/10/28/harmonyOS/%E9%B8%BF%E8%92%99%E7%BB%93%E8%AF%BE%E8%AF%81/" title="结课证书"><img class="cover" src="/blog/img/library1.jpeg" onerror="onerror=null;src='/blog/img/friend_404.gif'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">结课证书</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/blog/img/head.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">侯玉东</div><div class="author-info__description">生命不息，奋斗不止</div></div><div class="card-info-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">70</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">18</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/houyudong1989"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/houyudong1989" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:420098321@qq.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎来到我的博客！！！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%A6%82%E8%BF%B0"><span class="toc-number">1.</span> <span class="toc-text">概述</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#context-%E4%BD%BF%E7%94%A8%E6%96%B9%E5%BC%8F"><span class="toc-number">2.</span> <span class="toc-text">context 使用方式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#ApplicationContext"><span class="toc-number">2.1.</span> <span class="toc-text">ApplicationContext</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#UIAbilityContext"><span class="toc-number">2.2.</span> <span class="toc-text">UIAbilityContext</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96-UIAbilityContext"><span class="toc-number">2.2.1.</span> <span class="toc-text">获取 UIAbilityContext</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%90%AF%E5%8A%A8%E4%B8%80%E4%B8%AA%E6%96%B0%E7%9A%84-UIAbility"><span class="toc-number">2.2.2.</span> <span class="toc-text">启动一个新的 UIAbility</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%8E%B7%E5%8F%96-UIAbility-%E8%BF%94%E5%9B%9E%E7%BB%93%E6%9E%9C"><span class="toc-number">2.2.3.</span> <span class="toc-text">获取 UIAbility 返回结果</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#AbilityStageContext"><span class="toc-number">2.3.</span> <span class="toc-text">AbilityStageContext</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ServiceExtensionContext"><span class="toc-number">2.4.</span> <span class="toc-text">ServiceExtensionContext</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/05/06/c++/5%E3%80%81%E5%AD%97%E7%AC%A6%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2/" title="字符和字符串"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="字符和字符串"/></a><div class="content"><a class="title" href="/blog/2024/05/06/c++/5%E3%80%81%E5%AD%97%E7%AC%A6%E5%92%8C%E5%AD%97%E7%AC%A6%E4%B8%B2/" title="字符和字符串">字符和字符串</a><time datetime="2024-05-06T11:15:27.280Z" title="发表于 2024-05-06 19:15:27">2024-05-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/05/06/c++/4%E3%80%81%E6%8C%87%E9%92%88%E5%92%8C%E5%87%BD%E6%95%B0%E6%8C%87%E9%92%88/" title="指针和函数指针"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="指针和函数指针"/></a><div class="content"><a class="title" href="/blog/2024/05/06/c++/4%E3%80%81%E6%8C%87%E9%92%88%E5%92%8C%E5%87%BD%E6%95%B0%E6%8C%87%E9%92%88/" title="指针和函数指针">指针和函数指针</a><time datetime="2024-05-06T11:14:29.047Z" title="发表于 2024-05-06 19:14:29">2024-05-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/05/05/python/7%E3%80%81m3u8%E8%A7%86%E9%A2%91%E6%A0%BC%E5%BC%8F/" title="m3u8格式"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="m3u8格式"/></a><div class="content"><a class="title" href="/blog/2024/05/05/python/7%E3%80%81m3u8%E8%A7%86%E9%A2%91%E6%A0%BC%E5%BC%8F/" title="m3u8格式">m3u8格式</a><time datetime="2024-05-05T01:43:26.865Z" title="发表于 2024-05-05 09:43:26">2024-05-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/04/30/android/charles%E5%AE%89%E5%8D%93%E6%89%8B%E6%9C%BA%E6%8A%93%E5%8C%85/" title="charles 抓包"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="charles 抓包"/></a><div class="content"><a class="title" href="/blog/2024/04/30/android/charles%E5%AE%89%E5%8D%93%E6%89%8B%E6%9C%BA%E6%8A%93%E5%8C%85/" title="charles 抓包">charles 抓包</a><time datetime="2024-04-30T06:49:29.279Z" title="发表于 2024-04-30 14:49:29">2024-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2024/04/26/python/13%E3%80%81playwright/" title="playwright"><img src="/blog/img/library1.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="playwright"/></a><div class="content"><a class="title" href="/blog/2024/04/26/python/13%E3%80%81playwright/" title="playwright">playwright</a><time datetime="2024-04-26T07:30:36.069Z" title="发表于 2024-04-26 15:30:36">2024-04-26</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2024 By 侯玉东</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="8873950678" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true"> </div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener
  btf.removeGlobalFnEvent('pjax')
  btf.removeGlobalFnEvent('themeChange')

  document.getElementById('rightside').classList.remove('rightside-show')
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()
})

document.addEventListener('pjax:error', e => {
  if (e.request.status === 404) {
    pjax.loadUrl('/blog/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>